package org.zheng.shop.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.zheng.shop.dto.ConsultationMessageDTO;
import org.zheng.shop.dto.ConsultationSessionDTO;
import org.zheng.shop.security.UserDetailsImpl;
import org.zheng.shop.service.ConsultationService;

/**
 * 咨询控制器 - 基于轮询的简单实现
 */
@RestController
@RequestMapping("/api/consultation")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ConsultationController {

    @Autowired
    private ConsultationService consultationService;

    /**
     * 创建或获取用户的活跃咨询会话
     */
    @PostMapping("/session")
    public ResponseEntity<?> createOrGetSession(@RequestBody Map<String, String> request,
                                              Authentication authentication) {
        try {
            System.out.println("创建会话请求: " + request);

            if (authentication == null) {
                System.out.println("认证信息为空");
                return ResponseEntity.status(401)
                    .body(Map.of("error", "用户未认证"));
            }

            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            System.out.println("当前用户: " + userDetails.getUsername() + ", ID: " + userDetails.getId());

            String title = request.get("title");
            System.out.println("会话标题: " + title);

            ConsultationSessionDTO session = consultationService.createOrGetActiveSession(
                userDetails.getId(), title);

            System.out.println("会话创建成功: " + session.getId());
            return ResponseEntity.ok(session);
        } catch (Exception e) {
            System.err.println("创建会话失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest()
                .body(Map.of("error", "创建会话失败: " + e.getMessage()));
        }
    }

    /**
     * 获取会话的新消息（轮询接口）
     */
    @GetMapping("/session/{sessionId}/messages")
    public ResponseEntity<?> getMessages(@PathVariable Long sessionId,
                                       @RequestParam(required = false) Long since,
                                       Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            
            // 验证用户权限
            if (!consultationService.canAccessSession(sessionId, userDetails.getId())) {
                return ResponseEntity.status(403)
                    .body(Map.of("error", "无权访问此会话"));
            }
            
            List<ConsultationMessageDTO> messages = consultationService.getMessagesSince(sessionId, since);
            return ResponseEntity.ok(messages);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取消息失败: " + e.getMessage()));
        }
    }

    /**
     * 发送消息
     */
    @PostMapping("/session/{sessionId}/message")
    public ResponseEntity<?> sendMessage(@PathVariable Long sessionId,
                                       @RequestBody Map<String, String> request,
                                       Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            String content = request.get("content");
            
            if (content == null || content.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of("error", "消息内容不能为空"));
            }
            
            // 验证用户权限
            if (!consultationService.canAccessSession(sessionId, userDetails.getId())) {
                return ResponseEntity.status(403)
                    .body(Map.of("error", "无权访问此会话"));
            }
            
            // 确定发送者类型
            boolean isAdmin = userDetails.getAuthorities().stream()
                .anyMatch(auth -> "ROLE_ADMIN".equals(auth.getAuthority()));
            
            ConsultationMessageDTO message = consultationService.sendMessage(
                sessionId, userDetails.getId(), content.trim(), isAdmin);
            
            return ResponseEntity.ok(message);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "发送消息失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户的会话列表
     */
    @GetMapping("/sessions")
    public ResponseEntity<?> getUserSessions(Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            List<ConsultationSessionDTO> sessions = consultationService.getUserSessions(userDetails.getId());
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取会话列表失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员获取所有会话列表
     */
    @GetMapping("/admin/sessions")
    public ResponseEntity<?> getAllSessions(Authentication authentication) {
        try {
            List<ConsultationSessionDTO> sessions = consultationService.getAllSessions();
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取会话列表失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员接管会话
     */
    @PostMapping("/admin/session/{sessionId}/takeover")
    public ResponseEntity<?> takeOverSession(@PathVariable Long sessionId,
                                           Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            consultationService.takeOverSession(sessionId, userDetails.getId());
            return ResponseEntity.ok(Map.of("message", "会话接管成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "接管会话失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员关闭会话
     */
    @PostMapping("/admin/session/{sessionId}/close")
    public ResponseEntity<?> closeSession(@PathVariable Long sessionId,
                                        Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            consultationService.closeSession(sessionId, userDetails.getId());
            return ResponseEntity.ok(Map.of("message", "会话关闭成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "关闭会话失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员删除已关闭的会话
     */
    @DeleteMapping("/admin/session/{sessionId}")
    public ResponseEntity<?> deleteSession(@PathVariable Long sessionId,
                                         Authentication authentication) {
        try {
            consultationService.deleteClosedSession(sessionId);
            return ResponseEntity.ok(Map.of("message", "会话删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "删除会话失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员批量删除已关闭的会话
     */
    @DeleteMapping("/admin/sessions/closed")
    public ResponseEntity<?> deleteAllClosedSessions(Authentication authentication) {
        try {
            int deletedCount = consultationService.deleteAllClosedSessions();
            return ResponseEntity.ok(Map.of("message", "批量删除完成", "deletedCount", deletedCount));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "批量删除失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员清理重复会话
     */
    @PostMapping("/admin/cleanup-duplicate-sessions")
    public ResponseEntity<?> cleanupDuplicateSessions(Authentication authentication) {
        try {
            int cleanedCount = consultationService.cleanupDuplicateSessions();
            return ResponseEntity.ok(Map.of("message", "清理完成", "cleanedCount", cleanedCount));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "清理失败: " + e.getMessage()));
        }
    }
}
